package com.xiaoxi.exam.utils;

import cn.xinzhili.xutils.core.ErrorCode;
import cn.xinzhili.xutils.core.FailureException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.StringUtils;

@Slf4j
public class SignUtils {

  private static final String API_KEY = "key";
  private static final String JOINT_CHARACTER = "=";
  private static final String AND_CHARACTER = "&";

  @SuppressWarnings("unchecked")
  public static String generateSign(Object obj, String apiKey) {

    Map map = JsonUtils.fromJson(JsonUtils.toJson(obj), Map.class);
    if (Objects.isNull(map)) {
      throw new FailureException(ErrorCode.INVALID_PARAMS);
    }
    ArrayList keyList = new ArrayList<>(map.keySet());
    Collections.sort(keyList);

    StringBuilder sb = new StringBuilder();
    log.info("sign start ---------------------");
    keyList.stream().filter(k -> {
      Object value = map.get(k);
      return Objects.nonNull(value) && !StringUtils.isEmpty(value.toString()) && !k.equals("sign");
    }).forEach(key -> {
      log.info("sign key : {} ==== {}", key, map.get(key));
      sb.append((key.toString())).append(JOINT_CHARACTER).append(map.get(key))
          .append(AND_CHARACTER);
    });
    sb.append(API_KEY).append(JOINT_CHARACTER).append(apiKey);
    return DigestUtils.md5Hex(sb.toString()).toUpperCase();
  }
}
